//
//  ZYPlaceholderTextView.swift
//  weibo007
//
//  Created by 陈宗毅 on 15/12/27.
//  Copyright © 2015年 czy. All rights reserved.
//

import UIKit

class ZYPlaceholderTextView: UITextView {


    var placeholderText:String?{
        didSet{
            placeholderLabel.text = placeholderText
            placeholderLabel.sizeToFit()
        }
    
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override init(frame: CGRect, textContainer: NSTextContainer?) {
        super.init(frame: frame, textContainer: textContainer)
        
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "textDidChange", name: UITextViewTextDidChangeNotification, object: nil)
        
        prepareUI()
    }
    
    deinit
    {
        NSNotificationCenter.defaultCenter().removeObserver(self)
        }
    
    func textDidChange()
    {
        placeholderLabel.hidden = hasText()
    }
    
   private func prepareUI(){
    //添加子控件
    self.addSubview(placeholderLabel)
    
    //添加约束
    placeholderLabel.translatesAutoresizingMaskIntoConstraints = false
    // 顶部和父控件顶部重合,有偏移
    addConstraint(NSLayoutConstraint(item: placeholderLabel, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Top, multiplier: 1, constant: 8))
    // 左边和父控件的左边重合,有偏移
    addConstraint(NSLayoutConstraint(item: placeholderLabel, attribute: NSLayoutAttribute.Left, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Left, multiplier: 1, constant: 5))
    
    
    }

    
    
    //MARK: - 懒加载
    /// 占位文本的label,最好是不要把placeholderLabel直接暴露出去.暴露出去后,别人有太多的修改权利
    private lazy var placeholderLabel:UILabel = {
        let placeholderLabel = UILabel()
        //设置占位文本
        placeholderLabel.font = UIFont.systemFontOfSize(18)
        placeholderLabel.textColor = UIColor.lightGrayColor()

        return placeholderLabel
        }()
}
